<template>
  <div class="contain">
    <!-- 显示摄像头视频流的元素 -->
    <video ref="video" autoplay playsinline :style="{width:width+'px',height:height+'px'}"></video>
    <!-- 显示识别结果 -->
    <div v-if="recognitionResult">
      <h3>识别结果:</h3>
      <pre>{{ recognitionResult }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted,reactive } from 'vue';

const video = ref(null); // 参考视频元素
const recognitionResult = ref(null); // 存储识别结果
let stream = null; // 存储媒体流
let captureInterval = null; // 定时器句柄
// 传出视频数据
  const emit = defineEmits(['sendID','sendBase'])
// 启动摄像头并显示视频流
const startCamera = async () => {
  try {
    // 请求访问摄像头
    stream = await navigator.mediaDevices.getUserMedia({ video: true });
    if (video.value) {
      video.value.srcObject = stream;
      
      // 确保视频流加载完成后开始自动捕捉
      video.value.onloadedmetadata = () => {
        captureInterval = setInterval(captureImage, 5000); // 每5秒捕捉一次
      };
    }
  } catch (error) {
    console.error('访问摄像头时出错:', error);
  }
};

// 停止摄像头并释放资源
const stopCamera = () => {
  if (stream) {
    // 停止所有媒体流轨道
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
    if (video.value) {
      // 清除视频元素的源
      video.value.srcObject = null;
    }
  }
  
  // 清除定时器
  if (captureInterval) {
    clearInterval(captureInterval);
  }
};

// 从视频流中捕捉图像并发送到识别 API
const captureImage = async () => {
  if (video.value) {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.width = video.value.videoWidth;
    canvas.height = video.value.videoHeight;
    context.drawImage(video.value, 0, 0, canvas.width, canvas.height);
    
    // 将画布内容转换为 Blob 并发送到识别 API
    canvas.toBlob(async (blob) => {
      const imageData = await blobToBase64(blob);
      try {
        const result = await recognizeIdCard(imageData);
        recognitionResult.value = result;
        console.log('身份证识别结果:', result.words_result.公民身份号码.words);
        // 将摄像头数据进行传输
        emit('sendID', result.words_result.公民身份号码.words)
        emit('sendBase', imageData)
        console.log(imageData);
        
         
        // 识别成功后停止摄像头
        if (result.words_result_num!==0) {
          stopCamera();
        }
      } catch (error) {
        console.error('识别失败:', error);
        // 识别失败时，可以选择继续捕捉图像
      }
    }, 'image/jpeg');
  }
};

// 将 Blob 转换为 Base64 字符串
const blobToBase64 = (blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
};
//获取页面宽高
const width = window.visualViewport.width*0.9;
const height = window.visualViewport.height*0.9;
console.log(`视角宽度: ${width}, 视角高度: ${height}`);



// 识别身份证
const recognizeIdCard = async (base64Image) => {
  try {
    const API_KEY = 'zWcPjp9bXu5SerJs8r1B6raC';
    const SECRET_KEY = '3CdC8n4LeYMGhOgIEMPvvTyhN9zLKnYR';
    const API_URL = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard';

    // 获取 access token
    let tokenResponse = await fetch(`http://localhost:3000/proxy?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`);
    if (!tokenResponse.ok) {
      throw new Error('获取 access token 失败');
    }
    let tokenData = await tokenResponse.json();
    let accessToken = tokenData.access_token;

    // 发送图像到 API
    let formData = new URLSearchParams();
    formData.append('image', base64Image);
    formData.append('id_card_side', 'front');  // 确保 'front' 或 'back' 是正确的

    let response = await fetch(`${API_URL}?access_token=${accessToken}`, {
      method: 'POST',
      body: formData
    });
    if (!response.ok) {
      throw new Error('识别请求失败');
    }
    return await response.json();
  } catch (error) {
    throw new Error('识别身份证时出错: ' + error.message);
  }
};

// 组件挂载时启动摄像头
onMounted(() => {
  startCamera();
});

// 组件卸载时停止摄像头
onUnmounted(() => {
  stopCamera();
});
</script>

<style scoped lang="less">
.contain {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 200%;
  height: 88%;
}

video {
  /* 填充整个视口高度 */
  position: absolute;
  left: -152%;
  top:-4%;
}
</style>
